﻿using Newtonsoft.Json;

namespace DesignModeConsole.创建型.原型模式;

/// <summary>
/// 原型模式
/// </summary>
internal class PrototypeService : IService
{
    public void Main()
    {
        var search = new SearchCollectService();
    }
}

public class SearchCollectService
{
    private Dictionary<string, SearchCollectDto> currKeywordSearch = new Dictionary<string, SearchCollectDto>();

    private long lastUpdateTime = -1;

    public void Refresh()
    {
        var newKeywordSearch = currKeywordSearch.Clone<Dictionary<string, SearchCollectDto>>();

        //从数据库查询更新的搜索数据  查询大于某一个时间点的数据集合
        var updateSearchKeyword = new List<SearchCollectDto>();
        var maxNewUpdateTime = lastUpdateTime;
        foreach (var item in updateSearchKeyword)
        {
            if (maxNewUpdateTime < item.LastSearchTime)
            {
                maxNewUpdateTime = item.LastSearchTime;
            }
            if (newKeywordSearch.ContainsKey(item.Keyword))
            {
                newKeywordSearch[item.Keyword]
                    .SetCount(item.Count)
                    .SetLastTime(item.LastSearchTime);
            }
            else
            {
                newKeywordSearch[item.Keyword] = item;
            }
        }

        //从数据库读取所有数据放到
    }
}

/// <summary>
/// 搜索类
/// </summary>
public class SearchCollectDto
{
    /// <summary>
    /// 关键字
    /// </summary>
    public string Keyword { get; set; }

    /// <summary>
    /// 搜索次数
    /// </summary>
    public int Count { get; set; }

    /// <summary>
    /// 最后一次搜索时间
    /// </summary>
    public long LastSearchTime { get; set; }

    public SearchCollectDto SetCount(int count)
    {
        Count += count;
        return this;
    }

    public SearchCollectDto SetLastTime(long lastTime)
    {
        LastSearchTime = lastTime;
        return this;
    }
}

public static class ObjectExtensions
{
    public static T Clone<T>(this object ob)
    {
        if (ob is null) return default;

        var jsonStr = JsonConvert.SerializeObject(ob);
        return JsonConvert.DeserializeObject<T>(jsonStr);
    }
}